package com.example.uniapp.activity.main;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.uniapp.R;
import com.example.uniapp.activity.userHome.UserAddCookbookActivity;
import com.example.uniapp.activity.frament.UserHomeFragment;
import com.example.uniapp.activity.frament.UserPersonCenterFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;

public class MainUserActivity extends AppCompatActivity {
    private int selectedItemId = R.id.user_bottom_menu_home; // 默认选择主页

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_user);

        //实现第一次访问加载界面
        FragmentManager fragment_container = getSupportFragmentManager();
        FragmentTransaction transaction = fragment_container.beginTransaction();
        transaction.replace(R.id.user_main_frame, new UserHomeFragment());
        transaction.commit();

        BottomNavigationView bottomNavigationView = findViewById(R.id.user_bottom_menu);
        bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                //获取当前选中的id
                FragmentManager fragment_container_2 = getSupportFragmentManager();
                FragmentTransaction transaction_2 = fragment_container_2.beginTransaction();
                int id = menuItem.getItemId();
                selectedItemId = id;

                //判断要跳转的界面
                if(id == R.id.user_bottom_menu_home) {
                    transaction_2.replace(R.id.user_main_frame, new UserHomeFragment());
                }
                if(id == R.id.user_bottom_menu_add_cookbook) {
                    //跳转到添加食谱界面
                    selectedItemId = R.id.user_bottom_menu_home; //如果是跳转到添加食谱界面，后续返回时是返回到主页
                    Intent intent = new Intent(MainUserActivity.this, UserAddCookbookActivity.class);
                    startActivity(intent);
                    return true;
                }
                if(id == R.id.user_bottom_menu_person_center) {
                    //添加到个人中心界面
                    transaction_2.replace(R.id.user_main_frame, new UserPersonCenterFragment());
                }
                transaction_2.commit();
                return true;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 恢复底部导航栏选中状态
        BottomNavigationView bottomNavigationView = findViewById(R.id.user_bottom_menu);
        bottomNavigationView.setSelectedItemId(selectedItemId);
    }
}